package com.example.contact.viewmodel

import android.util.Log
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.contact.repository.ContactRepository
import com.example.featuresdk.navigation.INavigationMediator
import com.example.contact.model.Contact
import com.example.featuresdk.event.ServiceMediator
import com.example.featuresdk.model.User
import com.example.featuresdk.repository.UserRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class ContactDetailViewModel @Inject constructor(
    userRepository: UserRepository,
    contactRepository: ContactRepository,
    navigationMediator: INavigationMediator,
    savedStateHandle: SavedStateHandle): ViewModel() {

    private val userId = savedStateHandle.get<Long>("id")

    private val externalTopicDetailScreen = "chat/topic/{id}/detail"

    val commands = object: ContactDetailCommands{
        override fun addContact(userId: Long) {
            launch {
                contactRepository.create(Contact(User.ME.id!!, userId))
//                //create a personal topic
                val user = userRepository.getOne(userId)
                ServiceMediator.call("topic/create", mutableMapOf<String,Any>().apply {
                    this["id"] = userId
                    this["title"] = user.nickname
                    this["logo"] = user.icon
                })
                startChat(userId)
            }
        }

        override fun startChat(userId: Long) {
            //navigate to the topic detail screen
            navigationMediator.navigate(externalTopicDetailScreen, userId.toString()){
                popUpTo(externalTopicDetailScreen){
                    inclusive = true
                }
                launchSingleTop = true
            }
        }

        override fun startCall(userId: Long) {

        }
    }

    val uiState = ContactDetailState()

    init {
        viewModelScope.launch {
            uiState.user = userRepository.getOne(userId!!)

            uiState.contact = contactRepository.getOne(User.ME.id!!, userId)

            //username calculation logic:
            //if the user is NOT my contact (uiState.contact == null)
            // or the user is my contact but i have not set a specific contact name
            //then use the user's nickname as username
            //otherwise use the specific contact name as username
            uiState.username.value = if(uiState.contact == null || uiState.contact!!.name.isNullOrEmpty()){
                uiState.user.nickname
            } else uiState.contact!!.name!!

            uiState.hasChatAccess.value = navigationMediator.hasRoute(externalTopicDetailScreen)
        }
    }

    private fun launch(action: suspend ()->Unit){
        viewModelScope.launch {
            try {
                action()
            }catch (e: CancellationException){
                //ignore
            } catch (t: Throwable){
                Log.e("TopicDetailViewModel","Error",t)
            }
        }
    }
}